package ar.com.photo_admin.persistence;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import ar.com.photo_admin.domain.Token;

public class TokenDAO {

	private SQLiteDatabase database;
	private TokenSQLiteHelper dateBaseHelper;

	public TokenDAO(Context context) {
		dateBaseHelper = new TokenSQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dateBaseHelper.getWritableDatabase();
	}

	public void close() {
		dateBaseHelper.close();
	}

	public Token saveOrUpdateToken(Token token) {
		ContentValues values = new ContentValues();
		
		values.put(TokenColumns.TOKEN.getName(), token.getToken());
		
		Long id = token.getId();
		
		if (id == null)		
			id = database.insert(TokenSQLiteHelper.TOKEN_TABLE, null, values);
		else
			database.update(TokenSQLiteHelper.TOKEN_TABLE, values, TokenColumns.ID_COLUMN.getName() 
					+ " = " + id, null);
		
		Cursor cursor = database.query(TokenSQLiteHelper.TOKEN_TABLE,
				TokenColumns.getAllColumns(), 
				TokenColumns.ID_COLUMN.getName() + " = " + id, 
				null, null, null, null);
		
		cursor.moveToFirst();
		token = cursorToToken(token, cursor);
		cursor.close();
		
		return token;
	}

	public void deleteToken(Token token) {
		Long id = token.getId();
		database.delete(TokenSQLiteHelper.TOKEN_TABLE, TokenColumns.ID_COLUMN.getName() 
				+ " = " + id, null);
	}
	
	public void deleteAllTokens() {
		database.delete(TokenSQLiteHelper.TOKEN_TABLE, null, null);
	}

	public List<Token> getAllTokens() {
		List<Token> tokens = new ArrayList<Token>();

		Cursor cursor = getAllTokensCursor();

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Token token = cursorToToken(cursor);
			tokens.add(token);
			cursor.moveToNext();
		}

		cursor.close();
		return tokens;
	}
	
	public Cursor getAllTokensCursor() {
		return database.query(TokenSQLiteHelper.TOKEN_TABLE,
				TokenColumns.getAllColumns(), null, null, null, null, null);
	}

	private Token cursorToToken(Cursor cursor) {
		Token token = new Token();
		return cursorToToken(token, cursor);
	}

	private Token cursorToToken(Token token, Cursor cursor) {
		Long id = cursor.getLong(0);
		String tokenValue = cursor.getString(1);
		Long eventId = cursor.getLong(2);
		
		token.setId(id);
		token.setToken(tokenValue);
		token.setEventId(eventId);

		return token;
	}
}
